import { createStore } from 'vuex'
import axios from 'axios'
export default createStore({
  state: {
    list:[],
    cartList:[], // 购物车的数据
  },
  mutations: {
    saveList(state,val){
      state.list = val
    },
    addCart(state,val){
      // console.log(val);
      // index > -1 说明商品已经存在
      let index = state.cartList.findIndex(item => item.id == val.id);
      // console.log(index);
      let obj = {
        ...val,
        ...{
          num: 1,
          check: false
        }
      }
      if (index>-1){
        state.cartList[index].num++;
        return
      }
      state.cartList.push(obj);
    },
    allCheck(state,bool){ // 全选的事件
      console.log('rtyuio');
      state.cartList.forEach(item => {
        item.check = bool
      })
    },
    delect(state){ // 批量删除
      state.cartList = state.cartList.filter(item => item.check == false)
    }
  },
  actions: {
   async getList({commit}){
      let { data } = await axios.get('data.json')
      // console.log(data);
      commit('saveList',data)
    }
  },
  modules: {
  }
})
